package com.example.wly.chapter4homework;

import android.Manifest;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity {
    int page=0;//页数
    int wordsPerPage=300;//每页显示的字数
    private TextView tvInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvInfo = (TextView) findViewById(R.id.tv_info);
        Button btnRead = (Button) findViewById(R.id.bt_read);

        tvInfo.setMovementMethod(ScrollingMovementMethod.getInstance());

        btnRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击按钮，读文本文件的内容
                //文件的位置storage/emulated/0/mysd.txt
                //文件中是字符
                //点击一次按钮，页数+1
                page++;
                String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/note.txt";
                String data = getcharDataFromFile(path);
                tvInfo.setText(data);

                int offset=tvInfo.getLineCount()*tvInfo.getLineHeight();
                if(offset>tvInfo.getHeight()){
                    tvInfo.scrollTo(0,tvInfo.getHeight()-offset);
                }
            }
        });

        //申请权限
        String[]perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if(!EasyPermissions.hasPermissions(this,perms)){
            EasyPermissions.requestPermissions(this,"write sd",1,perms);
        }
    }

    private String getcharDataFromFile(String path) {
        File file = new File(path);
        String data = "";//将文件中都出来的字符保存在字符串data中
        try {
            FileInputStream fis = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis,"utf-8"));

            //跳过当前页前面的所有页的数据
            br.skip((page-1)*wordsPerPage);
            for(int i = 0;i<wordsPerPage;i++){
                int c = br.read();//读入一个字符，读入的字符的编码保存在整型变量c中
                data=data+(char)c;//

            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
}

